const express = require('express')
const Result = require('../models/Result')
const {
  orLike,
  orLimit,
  queryTotal,
  querySqlTotal,
  querySql,
  insert,
  deleteData,
  update
} = require('../db/index')

const router = express.Router()

/**
 * 新增搜索历史
 */
router.post('/addHistory', async(req, res) => {
  let result = await insert(`insert into search_history(userId, name) values(${req.body.userId}, '${req.body.searchName}')`)

  new Result(result, '新增成功').success(res)
})

/**
 * 获取热门搜素
 */
router.get('/getHotSearch', async(req, res) => {
  let result = await querySql(`SELECT * FROM (SELECT name,count(1) count FROM search_history GROUP BY name) t ORDER BY count desc limit 0,10`)

  new Result(result, '获取热门搜索成功').success(res)
})

/**
 * 根据搜索关键字搜索歌曲
 */
router.post('/getSongSerch', async(req, res) => {
  let result = await querySql(`SELECT
      t1.*,
      t2.singerName,
      t3.albumName,
      t4.lyric
    FROM
      song t1
      LEFT JOIN singer t2 ON t1.singer = t2.id
      LEFT JOIN album t3 ON t1.album = t3.id
      LEFT JOIN lyric t4 ON t1.id = t4.songId
    WHERE
      CONCAT(name, t2.singerName, t3.albumName) LIKE '%${req.body.searchKey}%'`)

  result.forEach(item => {
    if(item.lyric) item.lyric = item.lyric.replace(/\r/g, '\n')
  })
  new Result(result, '查询成功').success(res)
})

/**
 * 根据搜索关键字搜索专辑
 */
router.post('/getAlbumSerch', async(req, res) => {
  let result = await querySql(`SELECT
      t1.*,
      t2.singerName
    FROM
      album t1
      LEFT JOIN singer t2 ON t1.singerId = t2.id
    WHERE
      albumName LIKE '%${req.body.searchKey}%'`)

  new Result(result, '查询成功').success(res)
})

module.exports = router